package com.glasses.business.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.glasses.business.R;
import com.glasses.business.activity.WebDetailActiviy;
import com.glasses.business.adapter.HomeAdapter;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.banner.Banner;
import com.glasses.business.banner.listener.OnBannerClickListener;
import com.glasses.business.banner.loader.FrescoImageLoader;
import com.glasses.business.base.AppBaseFragment;
import com.glasses.business.base.MyBaseAdapter;
import com.glasses.business.entity.HomeBanner;
import com.glasses.business.entity.HomeProduct;
import com.glasses.business.event.BussEvent;
import com.glasses.business.http.NetUtils;
import com.glasses.business.utils.Tools;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.neiquan.applibrary.wight.CustomViewPager;
import net.neiquan.applibrary.wight.RefreshLayout;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.ToastUtil;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.greenrobot.event.EventBus;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/6
 * Version：1.0
 */

public class HomeFragment extends AppBaseFragment implements RefreshLayout.RetryListener, XRecyclerView.LoadingListener, View.OnClickListener {

    @InjectView(R.id.recyclerview)
    XRecyclerView mRecyclerview;
    @InjectView(R.id.refesh_ly)
    RefreshLayout mRefeshLy;
    @InjectView(R.id.next_img)
    ImageView nextImg;
    private List<String> banners = new ArrayList<String>();
    private View homeHeadLL;
    private Banner customViewPager;
    private LinearLayout checkLight;
    private LinearLayout matchGlasses;
    private LinearLayout childGlasses;
    private HomeAdapter adapter;
    private LocationManager locationManager;
    private int pageNum = 0;
    private int pageSize = 10;
    private List<HomeBanner> list;

    @Override
    public int getRootViewId() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return R.layout.fragment_home;
    }

    public void onEventMainThread(BussEvent event) {
        if (event.getState() == BussEvent.JPush) {
            nextImg.setImageResource(R.mipmap.icon_xx);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void setViews() {
        adapter = new HomeAdapter(getActivity(), null);
        mRecyclerview.setAdapter(adapter);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setOrientation(StaggeredGridLayoutManager.VERTICAL);
        mRecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerview.setArrowImageView(R.mipmap.iconfont_downgrey);
        mRecyclerview.setHasFixedSize(true);
        mRecyclerview.setLayoutManager(layoutManager);
        mRefeshLy.setRetryListener(this);

        mRecyclerview.setLoadingListener(this);
        mRecyclerview.setLoadingMoreEnabled(false);
        mRecyclerview.setPullRefreshEnabled(true);
//        mRecyclerview.addItemDecoration(new SpaceItemDecoration(2));
        homeHeadLL = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home_head, null);
        mRecyclerview.addHeaderView(homeHeadLL);
        customViewPager = ((Banner) homeHeadLL.findViewById(R.id.customViewPager));
        checkLight = ((LinearLayout) homeHeadLL.findViewById(R.id.check_light));
        matchGlasses = ((LinearLayout) homeHeadLL.findViewById(R.id.match_glasses));
        childGlasses = ((LinearLayout) homeHeadLL.findViewById(R.id.child_glasses));
        checkLight.setOnClickListener(this);
        matchGlasses.setOnClickListener(this);
        childGlasses.setOnClickListener(this);
        nextImg.setOnClickListener(this);
        adapter.setOnItemClickListener(new MyBaseAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, List data, int position) {
                HomeProduct homeProduct = (HomeProduct) data.get(position);
                Bundle bundle = new Bundle();
                bundle.putInt("productId", homeProduct.getId());
                bundle.putInt("type", 2);
                open(new MatchGlassFragment(), bundle);
            }
        });
        customViewPager.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                Bundle bundle = new Bundle();
                HomeBanner banner = list.get(position - 1);
                bundle.putString("title", "资讯详情");
                bundle.putString("url", banner.getUrl());
                Intent intent = new Intent(getActivity(), WebDetailActiviy.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {
        if (MyApplication.getInstance().jpush) {
            nextImg.setImageResource(R.mipmap.icon_xx2);
        } else {
            nextImg.setImageResource(R.mipmap.icon_xx);
        }
//        banners.add("http://www.uimitrip.com/Uploads/Images/GoodsImage/5811b3fae9909.jpg");
//        banners.add("http://www.uimitrip.com/Uploads/Images/GoodsImage/5811b4285c5a7.jpg");
//        customViewPager.setImageUris(banners, null);
        getHomeDatas(true, pageNum, pageSize);
    }

    private void getHomeDatas(final boolean isRefush, final int pageNum, final int pageSize) {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().homeBanner(new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                list = (List<HomeBanner>) model.getModelList();
                banners.clear();
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        banners.add(list.get(i).getPicture());
                    }
                    customViewPager.setImages(banners).setDelayTime(3000)
//                .setBannerAnimation(FlipHorizontalTransformer.class)
                            .setImageLoader(new FrescoImageLoader())
                            .start();
                }
                NetUtils.getInstance().homeProduct(pageNum, pageSize, new NetCallBack() {
                    @Override
                    public void onSuccess(String response, String mssage, ResultModel model) {
                        Tools.dismissWaitDialog();
                        mRecyclerview.loadMoreComplete();
                        mRecyclerview.refreshComplete();
                        mRefeshLy.hideAll();
                        List<HomeProduct> products = (List<HomeProduct>) model.getModelList();
                        if (products != null && products.size() > 0) {
                            adapter.appendAll(products);
                        }
                        if (isRefush) {
                            adapter.clear();
                        }
                        adapter.append(products);
                        if (products == null || products.size() < 10) {
                            if (isRefush && (products == null || products.size() == 0)) {
//                        mRefeshLy.showEmptyView();
                                mRefeshLy.showFailView();
                            }
                            mRecyclerview.setLoadingMoreEnabled(false);
                        } else {
                            mRecyclerview.setLoadingMoreEnabled(true);
                        }
                    }

                    @Override
                    public void onFail(boolean dataError, int errorCode, String mssage) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast(mssage);
                        //                mRefeshLy.hideAll();
                        mRefeshLy.showFailView();
                        mRecyclerview.loadMoreComplete();
                        mRecyclerview.refreshComplete();
                    }
                }, HomeProduct.class);
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, HomeBanner.class);
    }

    @Override
    public boolean mainTabShow() {
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    @Override
    public void onRetryClick() {
        pageNum = 0;
        getHomeDatas(true, pageNum, pageSize);
    }

    @Override
    public void onRefresh() {
        pageNum = 0;
        getHomeDatas(true, pageNum, pageSize);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        getHomeDatas(false, pageNum, pageSize);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.check_light:
                open(new CheckLightListFragment());
//                open(new Switch3DFragment());
                break;
            case R.id.match_glasses:
                Bundle bundle = new Bundle();
                bundle.putInt("productId", -1);
                bundle.putInt("type", 0);
                open(new MatchGlassFragment(), bundle);
                break;
            case R.id.child_glasses:
                Bundle bundle_ = new Bundle();
                bundle_.putInt("productId", -1);
                bundle_.putInt("type", 1);
                open(new MatchGlassFragment(), bundle_);
                break;
            case R.id.next_img:
                open(new MsgListFragment());
                break;
        }
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

            if (parent.getChildPosition(view) != 0) {
                outRect.top = space;
                outRect.left = space;
                outRect.right = space;
                outRect.bottom = space;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        openGPSSettings();
    }

    private void openGPSSettings() {
        LocationManager alm = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            doWork();
            return;
        } else {
            Toast.makeText(getActivity(), "请开启GPS！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
        }

    }

    private void doWork() {
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        // 获得最好的定位效果
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        // 使用省电模式
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        // 获得当前的位置提供者
        String provider = locationManager.getBestProvider(criteria, true);
        // 获得当前的位置
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            MyApplication.getInstance().saveLocation(location);
            String url = "http://api.map.baidu.com/geocoder/v2/?ak=pPGNKs75nVZPloDFuppTLFO3WXebPgXg&callback=renderReverse&location=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&pois=0";
            new MyAsyncTask(url).execute();
        } else {
            locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        AppLog.e("1111=========requestCode==========" + requestCode + "=============resultCode===========" + resultCode + "===========data=========" + data);
        if (requestCode == 0) {
            doWork();
        }
    }


    private LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            //位置信息变化时触发
            if (location != null) {
                MyApplication.getInstance().saveLocation(location);
                String url = "http://api.map.baidu.com/geocoder/v2/?ak=pPGNKs75nVZPloDFuppTLFO3WXebPgXg&callback=renderReverse&location=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&pois=0";
                new MyAsyncTask(url).execute();
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            //GPS状态变化时触发
        }

        @Override
        public void onProviderEnabled(String provider) {
            //GPS禁用时触发
        }

        @Override
        public void onProviderDisabled(String provider) {
            //GPS开启时触发
        }
    };

    class MyAsyncTask extends AsyncTask<Void, Void, Void> {
        String url = null;//要请求的网址
        String str = null;//服务器返回的数据

        public MyAsyncTask(String url) {
            this.url = url;
        }

        @Override
        protected Void doInBackground(Void... params) {
//            str = GetHttpConnectionData.getData(url);
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                    long total = entity.getContentLength();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int count = 0;
                    int length = -1;
                    while ((length = is.read(buf)) != -1) {
                        baos.write(buf, 0, length);
                    }
                    str = new String(baos.toByteArray(), "utf-8");
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            try {
                str = str.replace("renderReverse&&renderReverse", "");
                str = str.replace("(", "");
                str = str.replace(")", "");
                JSONObject jsonObject = null;
                jsonObject = new JSONObject(str);
                JSONObject address = jsonObject.getJSONObject("result");
                String city = address.getString("formatted_address");
                String district = address.getString("sematic_description");
                AppLog.e("=============当前位置：" + city + district);
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onPostExecute(aVoid);
        }
    }
}
